<template>
  <div class="login-container">
    <div class="login-box">
      <h2 class="title">欢迎使用</h2>
      <h3 class="sub-title">陕汽智慧充电管理系统</h3>
      <p class="login-type">账号登录</p>

      <!-- 账号输入框 -->
      <input type="text" style="display: none;" autocomplete="username">
      <input type="password" style="display: none;" autocomplete="current-password">
      <div class="input-item">
        <input type="text" class="hidden-deceive-input" readonly />
        <input
          type="text"
          placeholder="请输入您的账号"
          v-model="account"
          class="input"
          name="temp_account" 
          id="temp_account" 
          autocomplete="off" 
          autocorrect="off"
          autocapitalize="off"
          spellcheck="false"
        />
      </div>

      <!-- 密码输入框 -->
      <div class="input-item">
        <input type="password" class="hidden-deceive-input" readonly />
        <input
          :type="showPassword ? 'text' : 'password'"
          placeholder="请输入您的密码"
          v-model="password"
          class="input password-input"
          name="temp_password" 
          id="temp_password" 
          autocomplete="off" 
          autocorrect="off"
          autocapitalize="off"
          spellcheck="false"
        />
        <!-- 密码显示切换图标 -->
        <span
          class="password-toggle-icon"
          @click="toggleShowPassword"
        ></span>
      </div>

      <!-- 验证码输入框与验证码图片 -->
      <div class="input-item captcha-row">
        <input
          type="text"
          placeholder="请输入验证码"
          v-model="captcha"
          class="input"
          autocomplete="off" 
          autocorrect="off"
          autocapitalize="off"
          spellcheck="false"
        />
        <canvas 
          ref="captchaCanvas" 
          class="captcha-img"
          width="150"  
          height="50"  
          @click="generateCaptcha(true)"  
          title="点击刷新验证码"
        ></canvas>
      </div>

      <!-- 同意条款 -->
      <div class="agree-row">
        <input
          type="checkbox"
          id="agree"
          v-model="isAgree"
          class="agree-checkbox"
          :disabled="!hasVisitedPrivacy"  
          @click="handleAgreeClick"     
        />
        <label for="agree" class="agree-label">
          已阅读并同意
          <router-link to="/privacy" class="privacy-link">《隐私声明》</router-link>
        </label>
      </div>

      <!-- 登录按钮 -->
      <button class="login-btn" @click="handleLogin">登录</button>

      <!-- 合作品牌 -->
      <div class="brands-container">
        <div class="cooperation">战略合作</div>
        <div class="cooperation-logos">
          <div class="logo-item">
            <img
              src="../../assets/sxqcLogo.png"
              alt="陕汽重卡logo"
              class="logo-img"
            />
          </div>
          <div class="logo-item">
            <img
              src="../../assets/tldLogo.png"
              alt="特来电logo"
              class="logo-img"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { userLogin } from '@/api/api';
import { showToast } from 'vant';
// import { Toast } from 'vant'
import Toast from 'vant/lib/Toast';
import { Notify } from 'vant';

// Vue.use(Notify);
// 导入样式（如果使用自动按需引入插件，可省略）
const router = useRouter()

// 表单数据 - 从sessionStorage恢复
const account = ref(sessionStorage.getItem('loginAccount') || '');
const password = ref(sessionStorage.getItem('loginPassword') || '');
const captcha = ref(sessionStorage.getItem('loginCaptcha') || ''); // 验证码输入内容保留
const isAgree = ref(sessionStorage.getItem('loginAgree') === 'true');
const showPassword = ref(false); 
const hasVisitedPrivacy = ref(false);

// 验证码相关（持久化关键状态）
const captchaCanvas = ref(null);
const currentCaptcha = ref(sessionStorage.getItem('currentCaptcha') || ''); // 验证码答案保留
const captchaImageData = ref(null); // 存储验证码图像数据

/**
 * 生成随机验证码
 */
function generateRandomCode(length = 4) {
  const chars = '0123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
  let result = '';
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * chars.length);
    result += chars[randomIndex];
  }
  return result;
}

/**
 * 绘制验证码（支持从缓存恢复）
 * @param {boolean} forceRefresh - 是否强制刷新验证码
 */
function generateCaptcha(forceRefresh = false) {
  const canvas = captchaCanvas.value;
  if (!canvas) return;

  const ctx = canvas.getContext('2d');
  const width = canvas.width;  
  const height = canvas.height; 

  // 若有缓存图像且不强制刷新，则恢复图像
  if (captchaImageData.value && !forceRefresh) {
    ctx.putImageData(captchaImageData.value, 0, 0);
    return;
  }

  // 否则生成新验证码
  ctx.clearRect(0, 0, width, height);
  ctx.fillStyle = '#f5f5f5';
  ctx.fillRect(0, 0, width, height);

  currentCaptcha.value = generateRandomCode();
  ctx.font = `bold ${height * 0.65}px Arial, SimHei`;
  const textMetrics = ctx.measureText(currentCaptcha.value);
  const x = (width - textMetrics.width) / 2;
  const y = height * 0.75; 

  currentCaptcha.value.split('').forEach((char, index) => {
    ctx.save();
    const angle = (Math.random() * 20 - 10) * Math.PI / 180;
    const charX = x + (textMetrics.width / currentCaptcha.value.length) * index;
    const colors = ['#333333', '#666666', '#999999', '#2c3e50', '#34495e'];
    ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)];
    ctx.translate(charX, y);
    ctx.rotate(angle);
    ctx.fillText(char, 0, 0);
    ctx.restore();
  });

  // 添加干扰线
  ctx.strokeStyle = 'rgba(0, 0, 0, 0.2)';
  ctx.lineWidth = 1.5;
  for (let i = 0; i < 2; i++) {
    ctx.beginPath();
    ctx.moveTo(Math.random() * width, Math.random() * height);
    ctx.lineTo(Math.random() * width, Math.random() * height);
    ctx.stroke();
  }

  // 添加噪点
  for (let i = 0; i < 50; i++) {
    ctx.fillStyle = `rgba(${Math.random() * 100}, ${Math.random() * 100}, ${Math.random() * 100}, 0.2)`;
    ctx.fillRect(Math.random() * width, Math.random() * height, 2, 2);
  }

  // 保存图像数据和验证码答案到缓存
  captchaImageData.value = ctx.getImageData(0, 0, width, height);
  sessionStorage.setItem('currentCaptcha', currentCaptcha.value);
}

/**
 * 表单验证
 */
function validateForm() {
  if (!account.value.trim()) {
    alert('请填写账号信息');
    return false;
  }
  
  if (!password.value.trim()) {
    alert('请填写密码信息');
    return false;
  }
  
  if (!captcha.value.trim()) {
    alert('请填写验证码信息');
    return false;
  }
  
  if (captcha.value.trim().toUpperCase() !== currentCaptcha.value.toUpperCase()) {
    alert('验证码错误，请重新输入');
    generateCaptcha(true); // 验证失败时强制刷新
    captcha.value = '';
    return false;
  }
  
  if (!isAgree.value) {
    alert('需要阅读并同意隐私协议');
    return false;
  }
  
  return true;
}

/**
 * 登录逻辑
 */
 const handleLogin = async () => {
        // router.push({ name: 'Home' });
  if (!validateForm()) return;

  const loginParams = {
    userAccount: account.value,
    password: password.value,
  };
  console.log('登录参数：', loginParams);
  try {
    // 调用登录接口
    const response = await userLogin(loginParams);
    // 处理后端响应（需与实际接口返回格式匹配）
    if (response.code === 200) {
      // 关键操作：登录新账号前，先清除旧账号的 token
      localStorage.removeItem('token'); // 清除旧 token
      sessionStorage.removeItem('userInfo'); // 清除旧用户信息
      // 保存token和用户信息
      const { token, userInfo } = response.data;
      localStorage.setItem('token', token);
      sessionStorage.setItem('userInfo', JSON.stringify(userInfo));
      // 清除缓存数据
      ['loginAccount', 'loginPassword', 'loginCaptcha', 'loginAgree', 'currentCaptcha'].forEach(key => {
        sessionStorage.removeItem(key);
      });
      router.push({ name: 'Home' });
    } else if ( response.code === 1000){
      alert("该用户不存在");
    } else if (response.code === 1001) {
       alert('密码错误请重试');
    }  else if ( response.code === 1002 ) {
       alert("登录异常，请稍后重试");
    }
  } catch (error) { 
    // router.push({ name: 'Home' });
    console.error('登录接口调用失败：', error);
  }
 }
/**
 * 切换密码显示状态
 */
function toggleShowPassword() {
  showPassword.value = !showPassword.value;
}

/**
 * 复选框点击事件
 */
const handleAgreeClick = (e) => {
  if (!hasVisitedPrivacy.value) {
    e.preventDefault();
    alert('请先阅读《隐私声明》后再勾选同意');
  }
};

// 监听表单数据变化，实时持久化
watch(account, (newVal) => {
  sessionStorage.setItem('loginAccount', newVal);
});
watch(password, (newVal) => {
  sessionStorage.setItem('loginPassword', newVal);
});
watch(captcha, (newVal) => {
  sessionStorage.setItem('loginCaptcha', newVal);
});
watch(isAgree, (newVal) => {
  sessionStorage.setItem('loginAgree', newVal);
});

// 初始化
onMounted(() => {
  nextTick(() => {
    // 恢复验证码（首次加载或无缓存时生成新验证码）
    if (currentCaptcha.value && captchaCanvas.value) {
      generateCaptcha(); // 从缓存恢复
    } else {
      generateCaptcha(true); // 强制生成新验证码
    }
  });
  // 读取隐私页访问状态
  hasVisitedPrivacy.value = sessionStorage.getItem('hasReadPrivacy') === 'true';
});

// 监听路由变化（从隐私页返回时恢复验证码）
watch(
  () => router.currentRoute.value.path,
  (newPath) => {
    if (newPath === '/login') {
      hasVisitedPrivacy.value = sessionStorage.getItem('hasReadPrivacy') === 'true';
      // 路由返回后恢复验证码图像
      nextTick(() => {
        generateCaptcha();
      });
    }
  }
);
</script>

<style scoped>
/* 样式部分保持不变 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.login-container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/loginBg.png') no-repeat center/cover;
  background-attachment: fixed;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding: 20px;
}

.login-box {
  width: 100%;
  max-width: 500px;
  border-radius: 12px;
  padding: 20px 20px 10px;
  text-align: center;
  color: #fff;
  margin-top: 10px; /* 关键：减少顶部外边距 */
  display: flex;
  flex-direction: column;
  min-height: 650px; 
}

.title {
  font-size: 26px;
  margin-bottom: 8px; /* 减少标题底部间距 */
  font-weight: 600;
}

.sub-title {
  font-size: 18px;
  margin-bottom: 15px; /* 减少子标题底部间距 */
}

.login-type {
  font-size: 16px;
  margin-bottom: 10px; /* 减少登录类型底部间距 */
  text-align: center;
  padding-left: 0;
}


.input-item {
  position: relative;
  margin-bottom: 12px; /* 减少输入框之间的间距 */
  width: 100%;
}

.hidden-deceive-input {
  position: absolute;
  width: 0;
  height: 0;
  opacity: 0;
  pointer-events: none;
  border: none;
}

.input {
  width: 100%;
  padding: 14px 15px;
  appearance: none;
  outline: none;
  border: none;
  border-bottom: 1px solid #fff;
  background-color: transparent;
  font-size: 15px;
  color: #fff;
  transition: border-color 0.3s;
}

:deep(.input)::placeholder {
  color: hsl(0, 33%, 99%);
  font-size: 14px;
}

.password-input {
  padding-right: 45px;
}

.input:focus {
  border-bottom-color: #007bff;
  outline: none;
}

.captcha-row {
  display: flex;
  align-items: center;
  gap: 10px;
}

.captcha-img {
  cursor: pointer;
  border-radius: 4px;
}

.password-toggle-icon {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  width: 24px;
  height: 24px;
  cursor: pointer;
  background-image: url('@/assets/password.png');
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

:deep(.input-item:has(.password-input[type="text"]) .password-toggle-icon) {
  background-image: url('@/assets/password1.png');
}

.agree-row {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.agree-checkbox {
  margin-right: 8px;
  width: 16px;
  height: 16px;
}

.agree-checkbox:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.privacy-link {
  color: #007bff;
  text-decoration: underline;
  margin-left: 2px;
}

.login-btn {
  background: rgba(178, 208, 255, 0.1);
  backdrop-filter: blur(10px);
  width: 100%;
  padding: 14px;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 17px;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-bottom: 20px; 
}

.login-btn:hover {
  background-color: rgba(178, 208, 255, 0.4);
}

.login-btn:active {
  background-color: transparent;
  backdrop-filter: none;
}

.brands-container {
  margin-top: 40px; /* 减少品牌区顶部间距 */
  padding-bottom: 20px; 
}
.cooperation {
  margin: 15px 0 20px; 
  font-size: 14px;
  color: rgba(255, 255, 255, 0.7);
}

.cooperation-logos {
  display: flex;
  justify-content: space-around;
  padding: 0 20px;
}

.logo-item {
  text-align: center;
}

.logo-img {
  width: 70px;
  height: 70px;
  margin-bottom: 15px; 
  object-fit: contain;
}

@media (max-width: 375px) {
  .login-box {
    padding: 15px 15px 5px;
    margin-top: 20px;
    min-height: 550px;
  }

  .brands-container {
    padding-bottom: 10px; 
    margin-top: 20px; 
  }

  .cooperation {
    margin: 10px 0 15px;
  }

  .logo-img {
    width: 60px;
    height: 60px;
    margin-bottom: 10px;
  }
}
</style>